﻿//创建时间: 2011-04-25
//创建作者: 李 城
//功能说明: CMS安装程序  很大一部分程序来源于Discuz安装源码
//最后修改: 2011-04-25
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;

using TRPOP.CMS.Model;
using TRPOP.CMS.Business;
using TRPOP.CMS.Plugin;
using TRPOP.CMS.Log;
using System.Text;
using System.IO;
using System.Collections;
using System.Data.SqlClient;
using System.Data;
using System.Data.Common;
using TRPOP.Common;

namespace TRPOP.CMS.Web.ExtraBus
{
    /// <summary>
    /// 逻辑处理继承的基类
    /// </summary>
    public class Page_Instal : Page_InstalBase
    {
        protected string sqlServerIP = "";
        protected string dataBaseName = "";
        protected string sqlUID = "";
        protected string sqlPassword = "";
        protected string sqlPasswordConfirm = "";
        protected string tablePrefix = "";
        protected string dnOwner = "dbo";
        protected string sqlVersion = "";
        private SqlConnection connection = new SqlConnection();
        protected string connectionString = "";
        protected string commandText = "";
        public static int isError = 0;
        public static string mdataBaseName = "York_CMS";
        protected System.Web.UI.HtmlControls.HtmlInputCheckBox cb_newDatabase;
        /// <summary>
        /// 是否能够连得上 http://admin.yorknet.cn/install/ServerRecCount.aspx?test=true
        /// </summary>
        protected bool mBlnIsOnline = IsOnline();
        //step 4
        protected string forumPath = SystemInfoHelper.getSystemInfo().CMSDomian;

        protected void Page_Load(object sender, EventArgs e)
        {
            FillDatabaseInfo();
            tablePrefix = SystemInfoHelper.getSystemInfo().DBprefixTableName;
            if (!IsPostBack)
            {
                if (Request.QueryString["type"] == "unchecked")
                {
                    CheckBoxUnchecked();
                }
                else if (Request.QueryString["type"] == "checked")
                {
                    CheckBoxChecked();
                }
                if (Request.QueryString["checkForumPath"] == "exists")
                    CheckForumPath(Request.QueryString["forumpath"]);
            }
        }
        #region 是否能够连得上 http://admin.yorknet.cn/install/ServerRecCount.aspx?test=true
        protected static bool IsOnline()
        {
            string strReturn = TRPOP.Common.DownURLFile.ReadUrlFile("http://admin.yorknet.cn/install/ServerRecCount.aspx?test=true");
            return strReturn.StartsWith("无法访问") == false;
        }
        #endregion

        #region step4
        /// <summary>
        /// 检查论坛路径是否正确
        /// </summary>
        /// <returns>false为不正确</returns>
        protected void CheckForumPath(string ntPath)
        {
            Response.Write("{\"Result\":true}");
            Response.End();
        }

        protected void Setup(object sender, EventArgs e)
        {
            SystemInfoHelper.getSystemInfo().CMSDomian = Request["ntPath"];
            ExeSQLfiles();
            Server.Transfer("succeed.aspx", true);
        }
        /// <summary>
        /// 运行含有GO命令的多条SQL命令
        /// </summary>
        /// <param name="commandText">SQL命令字符串</param>
        public void ExecuteCommandWithSplitter(string commandText)
        {
            ExecuteCommandWithSplitter(commandText, "\r\nGO");
        }
        /// <summary>
        /// 运行含有GO命令的多条SQL命令
        /// </summary>
        /// <param name="commandText">SQL命令字符串</param>
        /// <param name="splitter">分割字符串</param>
        public void ExecuteCommandWithSplitter(string commandText, string splitter)
        {
            int startPos = 0;
            do
            {
                int lastPos = commandText.IndexOf(splitter, startPos);
                int len = (lastPos > startPos ? lastPos : commandText.Length) - startPos;
                string query = commandText.Substring(startPos, len);
                if (query.Trim().Length > 0)
                {
                    try
                    {
                        ExecuteNonQuery(CommandType.Text, query);
                    }
                    catch (Exception ex) { throw ex; }
                }
                if (lastPos == -1)
                    break;
                else
                    startPos = lastPos + splitter.Length;
            } while (startPos < commandText.Length);
        }
        public int ExecuteNonQuery(CommandType commandType, string commandText)
        {
            ExcuteSQL(commandText, SystemInfoHelper.getSystemInfo().CMSDataBaseConnection);
            return 1;
        }

        /// <summary>
        /// 建表和存储过程
        /// </summary>
        private void ExeSQLfiles()
        {
            #region 执行SQL
            StringBuilder sb = new StringBuilder();
            for (int i = 1; i <= 5; i++)
            {
                using (StreamReader objReader = new StreamReader(Common.Util.GetMapPath("sqlscript/sqlserver/" + i.ToString() + ".sql"), Encoding.UTF8))
                {
                    sb.Append(objReader.ReadToEnd());
                    objReader.Close();
                }
                ExecuteCommandWithSplitter(keysReplace(sb.ToString()));
                sb.Remove(0, sb.Length);
            }
            #endregion
        }
        public string keysReplace(string strSQL)
        {
            return strSQL.Replace("http://cms.york.com", SystemInfoHelper.getSystemInfo().CMSDomian)
                         .Replace("cms_", SystemInfoHelper.getSystemInfo().DBprefixTableName.ToLower() + "_")
                         .Replace("'admin'", "'" + Request["adminName"] + "'")
                         .Replace("e10adc3949ba59abbe56e057f20f883e", Request["adminPassword"].MD5Normal())
                         .Replace("\r\ngo", "\r\nGO");
        }
        #endregion

        #region 删除关键文件
        public string DeleteAllfiles()
        {
            TRPOP.Common.FileUtil.DeleteDirectory(Common.Util.GetMapPath("/install/sqlscript/sqlserver/1.sql"));
            TRPOP.Common.FileUtil.DeleteDirectory(Common.Util.GetMapPath("/install/sqlscript/sqlserver/2.sql"));
            TRPOP.Common.FileUtil.DeleteDirectory(Common.Util.GetMapPath("/install/sqlscript/sqlserver/3.sql"));
            TRPOP.Common.FileUtil.DeleteDirectory(Common.Util.GetMapPath("/install/sqlscript/sqlserver/4.sql"));
            TRPOP.Common.FileUtil.DelFile(Common.Util.GetMapPath("/install/index.aspx"));
            TRPOP.Common.FileUtil.DelFile(Common.Util.GetMapPath("/install/step2.aspx"));
            TRPOP.Common.FileUtil.DelFile(Common.Util.GetMapPath("/install/step3.aspx"));
            TRPOP.Common.FileUtil.DelFile(Common.Util.GetMapPath("/install/step4.aspx"));
            TRPOP.Common.FileUtil.DelFile(Common.Util.GetMapPath("/install/succeed.aspx"));
            return "删除成功";
        }
        #endregion

        #region 数据库的操作基本方法

        /// <summary>
        /// 检测连接并执行数据库相关操作
        /// </summary>
        /// <param name="dataSource">数据库地址</param>
        /// <param name="userID">数据库账号</param>
        /// <param name="password">数据库账号密码</param>
        /// <param name="databaseName">数据库名</param>
        /// <param name="tablePrefix">表前缀</param>
        /// <returns>0，1，2</returns>0：用户名或密码错误；1：指定的数据库不存在；2：都存在
        protected void CheckConnection(object sender, EventArgs e)
        {
            #region 检查信息
            if (!cb_newDatabase.Checked)
            {
                #region 没有选择新建数据库的操作
                EditDntConfig(Request["sql_ip"], Request["sql_username"], Request["sql_password"], Request["sql_name"], Request["table_prefix"], Request["sql_owner"]);
                GetSqlVersion(connectionString);
                ClientScript.RegisterStartupScript(typeof(Page), "error", "location.href='step4.aspx'", true);
                #endregion
            }
            else
            {
                #region 选择新建数据库的操作
                if (!CheckDatabaseUserInfo())//所填用户不存在或者密码错误
                {
                    #region
                    CreateDatabaseUser();//创建SQL登录名
                    if (CheckDatabaseExistsByDbManager() == 0)//指定数据库不存在
                    {
                        CreateDatabase();//创建指定数据库
                        CreateUserMap();//设置新创建的SQL用户的映射
                        EditDntConfig(Request["sql_ip"], Request["sql_username"], Request["sql_password"], Request["sql_name"], Request["table_prefix"], Request["sql_owner"]);
                        ClientScript.RegisterStartupScript(typeof(Page), "error", "location.href='step4.aspx'", true);
                    }
                    else
                    {
                        DeleteDatabase();//删除数据库
                        CreateDatabase();//创建数据库
                        if (Request["sql_username"].Trim() != "sa")
                        {
                            CreateUserMap();//设置新创建的SQL用户的映射
                        }
                        EditDntConfig(Request["sql_ip"], Request["sql_username"], Request["sql_password"], Request["sql_name"], Request["table_prefix"], Request["sql_owner"]);
                        ClientScript.RegisterStartupScript(typeof(Page), "error", "location.href='step4.aspx'", true);
                    }
                    #endregion
                }
                else
                {
                    if (CheckDatabaseExistsByDbManager() == 0)//指定数据库不存在
                    {
                        #region 创建数据库
                        CreateDatabase();//创建数据库
                        if (Request["sql_username"].Trim() != "sa")
                        {
                            CreateUserMap();//设置新创建的SQL用户的映射
                        }
                        #endregion
                        EditDntConfig(Request["sql_ip"], Request["sql_username"], Request["sql_password"], Request["sql_name"], Request["table_prefix"], Request["sql_owner"]);
                        ClientScript.RegisterStartupScript(typeof(Page), "error", "location.href='step4.aspx'", true);
                    }
                    else
                    {
                        DeleteDatabase();//删除数据库
                        CreateDatabase();//创建数据库
                        if (Request["sql_username"].Trim() != "sa")
                        {
                            CreateUserMap();//设置新创建的SQL用户的映射
                        }
                        EditDntConfig(Request["sql_ip"], Request["sql_username"], Request["sql_password"], Request["sql_name"], Request["table_prefix"], Request["sql_owner"]);
                        ClientScript.RegisterStartupScript(typeof(Page), "error", "location.href='step4.aspx'", true);
                    }
                }
                #endregion
            }
            #endregion
        }

        /// <summary>
        /// 创建用户映射
        /// </summary>
        protected void CreateUserMap()
        {
            connectionString = string.Format(@"Data Source={0};User ID={1};Password={2};Initial Catalog={3};Pooling=false",
                                              Request["sql_ip"], Request["sql_manager"], Request["sql_managerpassword"], "master");
            GetSqlVersion(connectionString);
            if (sqlVersion.Contains("2000"))
                commandText = string.Format("USE [{0}];EXEC dbo.sp_grantdbaccess @loginame = N'{1}', @name_in_db = N'{1}';EXEC sp_addrolemember 'db_datareader', '{1}';EXEC sp_addrolemember 'db_datawriter', '{1}';EXEC sp_addrolemember 'db_ddladmin', '{1}';EXEC sp_addrolemember 'db_owner', '{1}'",
                                             Request["sql_name"], Request["sql_username"]);
            else
                commandText = string.Format("USE [{0}]; CREATE USER [{1}] FOR LOGIN [{1}];EXEC sp_addrolemember 'db_datareader', '{1}';EXEC sp_addrolemember 'db_datawriter', '{1}';EXEC sp_addrolemember 'db_ddladmin', '{1}';EXEC sp_addrolemember 'db_owner', '{1}'",
                                                 Request["sql_name"], Request["sql_username"]);
            try
            {
                ExcuteSQL(commandText, connectionString);//设置新创建的SQL用户的映射
            }
            catch
            {
                ClientScript.RegisterStartupScript(typeof(Page), "error", "alert('创建数据库用户映射失败，请检查数据库管理员权限！或者该用户映射已经存在')", true);
                return;
            }
        }

        /// <summary>
        /// 创建数据库
        /// </summary>
        protected void CreateDatabase()
        {
            connectionString = string.Format(@"Data Source={0};User ID={1};Password={2};Initial Catalog={3};Pooling=false",
                                                  Request["sql_ip"], Request["sql_manager"], Request["sql_managerpassword"], "master");
            commandText = string.Format("CREATE DATABASE [{0}]", Request["sql_name"]);
            try
            {
                ExcuteSQL(commandText, connectionString);//执行创建数据库的TSQL；
            }
            catch
            {
                ClientScript.RegisterStartupScript(typeof(Page), "error", "alert('创建数据库失败，管理员密码填写错误！')", true);
                return;
            }
        }

        /// <summary>
        /// 删除数据库
        /// </summary>
        protected void DeleteDatabase()
        {
            connectionString = string.Format(@"Data Source={0};User ID={1};Password={2};Initial Catalog={3};Pooling=false",
                                              Request["sql_ip"], Request["sql_manager"], Request["sql_managerpassword"], "master");
            GetSqlVersion(connectionString);
            if (sqlVersion.Contains("2000"))
                commandText = string.Format("EXEC msdb.dbo.sp_delete_database_backuphistory @db_nm = '{0}';ALTER DATABASE [{0}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;DROP DATABASE [{0}]"
                                            , Request["sql_name"]);
            else
                commandText = string.Format("EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = '{0}';ALTER DATABASE [{0}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;DROP DATABASE [{0}]"
                                            , Request["sql_name"]);
            try
            {
                ExcuteSQL(commandText, connectionString);//执行删除数据库
            }
            catch
            {
                ClientScript.RegisterStartupScript(typeof(Page), "error", "alert('删除数据库失败，请检查数据库管理员权限！')", true);
                return;
            }
        }

        /// <summary>
        /// 用数据库管理员的账号检测数据库是否存在
        /// </summary>
        /// <returns></returns>
        protected int CheckDatabaseExistsByDbManager()
        {
            int result = 0;
            try
            {
                connectionString = string.Format(@"Data Source={0};User ID={1};Password={2};Initial Catalog={3};Pooling=false",
                                          Request["sql_ip"], Request["sql_manager"], Request["sql_managerpassword"], Request["sql_name"]);
                commandText = string.Format("SELECT DB_ID('{0}')", Request["sql_name"]);
                result = ExcuteReader(commandText, connectionString);
                EditDntConfig(Request["sql_ip"], Request["sql_username"], Request["sql_password"], Request["sql_name"], Request["table_prefix"], Request["sql_owner"]);
            }
            catch (Exception)
            {
                return result;
            }
            return result;
        }

        /// <summary>
        /// 创建数据库登录用户
        /// </summary>
        protected void CreateDatabaseUser()
        {
            connectionString = string.Format(@"Data Source={0};User ID={1};Password={2};Initial Catalog={3};Pooling=false",
                                              Request["sql_ip"], Request["sql_manager"], Request["sql_managerpassword"], "master");
            GetSqlVersion(connectionString);
            if (sqlVersion.Contains("2000"))
                commandText = string.Format(@"USE [master]; EXEC master.dbo.sp_addlogin @loginame = N'{0}', @passwd = N'{1}', @defdb = N'master'", Request["sql_username"], Request["sql_password"]);
            else
                commandText = string.Format(@"USE [master]; CREATE LOGIN [{0}] WITH PASSWORD='{1}', DEFAULT_DATABASE=[master], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF", Request["sql_username"], Request["sql_password"]);
            try
            {
                ExcuteSQL(commandText, connectionString);
            }
            catch
            {
                ClientScript.RegisterStartupScript(typeof(Page), "error", "alert('创建数据库登录用户失败，管理员密码填写错误！')", true);
                return;
            }
        }


        /// <summary>
        /// 检测数据库版本
        /// </summary>
        /// <param name="commandText">t-sql</param>
        /// <param name="connectionString">数据库连接串</param>
        protected void GetSqlVersion(string connectionString)
        {
            try
            {
                if (connection.State == ConnectionState.Open)
                    connection.Close();
                connection.ConnectionString = connectionString;
                connection.Open();
                SqlCommand sqlCommand = new SqlCommand("SELECT @@VERSION", connection);
                sqlVersion = sqlCommand.ExecuteScalar().ToString().Trim();
                sqlCommand.Connection.Close();
            }
            catch (Exception)
            {
                ClientScript.RegisterStartupScript(typeof(Page), "error", "alert('检查数据库版本失败,用户没有权限或登陆失败')", true);
                return;
            }
        }
        /// <summary>
        /// 将用户填写的数据库信息写入DNT.config文件
        /// </summary>
        /// <param name="dataSource">数据库地址</param>
        /// <param name="userID">数据库账号</param>
        /// <param name="password">数据库账号密码</param>
        /// <param name="databaseName">数据库名</param>
        /// <param name="tablePrefix">表前缀</param>
        protected void EditDntConfig(string dataSource, string userID, string password, string databaseName, string tablePrefix, string sql_owner)
        {
            connectionString = string.Format(@"Data Source={0};User ID={1};Password={2};Initial Catalog={3};Pooling=true",
                                             dataSource, userID, password, databaseName);
            SystemInfoHelper.getSystemInfo().CMSDataBaseConnection = connectionString;
            SystemInfoHelper.getSystemInfo().DBprefixTableName = tablePrefix;
        }

        /// <summary>
        /// 从配置文件中的连接字符串填充界面上的数据库配置信息
        /// </summary>
        protected void FillDatabaseInfo()
        {
            string connectionstring = SystemInfoHelper.getSystemInfo().CMSDataBaseConnection;
            foreach (string info in connectionstring.Split(';'))
            {
                if (info.ToLower().IndexOf("data source") >= 0)
                {
                    sqlServerIP = info.Split('=')[1].Trim();
                    continue;
                }
                if (info.ToLower().IndexOf("initial catalog") >= 0)
                {
                    dataBaseName = info.Split('=')[1].Trim();
                    continue;
                }
                if (info.ToLower().IndexOf("user id") >= 0)
                {
                    sqlUID = info.Split('=')[1].Trim();
                    continue;
                }
                if (info.ToLower().IndexOf("password") >= 0)
                {
                    sqlPassword = info.Split('=')[1].Trim();
                    continue;
                }
            }
        }

        /// <summary>
        /// 没有选择自动创建数据库时,需要检测的内容,ajax使用
        /// </summary>
        protected void CheckBoxUnchecked()
        {
            if (CheckDatabaseUserInfo() && CheckDatabaseExists() == 0)
                return;
        }

        /// <summary>
        /// 测试用户填写的数据库账号和密码是否正确
        /// </summary>
        /// <returns>false:数据库用户名或密码错误</returns>
        protected bool CheckDatabaseUserInfo()
        {
            try
            {
                if ((Request.QueryString["type"] == "unchecked") || Request.QueryString["type"] == "checked")
                {
                    connection.ConnectionString = string.Format(@"Data Source={0};User ID={1};Password={2};Initial Catalog={3};Pooling=false",
                                                  Request.QueryString["sql_ip"], Request.QueryString["sql_username"], Request.QueryString["sql_password"], "master");
                    connection.Open();
                }
                else
                {
                    connection.ConnectionString = string.Format(@"Data Source={0};User ID={1};Password={2};Initial Catalog={3};Pooling=false",
                                                  Request["sql_ip"], Request["sql_username"], Request["sql_password"], "master");
                    connection.Open();
                }
            }
            catch (Exception)
            {
                if ((Request.QueryString["type"] == "unchecked") || Request.QueryString["type"] == "checked")
                {
                    Response.Write("{\"Result\":false,\"Message\":\"数据库用户名或者密码错误！请重新填写\"}");
                    Response.End();
                }
                return false;
            }
            finally
            {
                connection.Close();
            }
            return true;
        }

        /// <summary>
        /// 执行SQL语句，用来测试指定数据库是否存在
        /// </summary>
        /// <param name="commandText">t-sql</param>
        protected void ExcuteSQL(string commandText, string connectionString)
        {
            try
            {
                if (connection.State == ConnectionState.Open)
                    connection.Close();
                connection.ConnectionString = connectionString;
                connection.Open();
                SqlCommand sqlCommand = new SqlCommand(commandText, connection);
                sqlCommand.ExecuteNonQuery();
                sqlCommand.Connection.Close();
            }
            catch (Exception oeException)
            {
                throw new Exception(oeException.Message, oeException);
            }
        }

        /// <summary>
        /// 检查数据库管理员的账号信息
        /// </summary>
        /// <returns></returns>
        protected bool CheckDbManagerInfo()
        {
            connectionString = string.Format(@"Data Source={0};User ID={1};Password={2};Initial Catalog={3};Pooling=false",
                                                              Request.QueryString["sql_ip"], Request.QueryString["sql_manager"], Request.QueryString["sql_managerpassword"], "master");
            commandText = string.Format("CREATE DATABASE [{0}]; DROP DATABASE [{0}]", "comsenz111");
            try
            {
                ExcuteSQL(commandText, connectionString);//执行创建数据库的TSQL；
            }
            catch
            {
                //ClientScript.RegisterStartupScript(typeof(Page), "error", "alert('创建数据库失败，管理员密码填写错误！')", true);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 执行TSQL并返回查询结果的第一行第一列的值
        /// </summary>
        /// <param name="commandText">TSQL</param>
        /// <param name="connectionString">连接串</param>
        /// <returns></returns>
        protected int ExcuteReader(string commandText, string connectionString)
        {
            int result = 0;
            try
            {
                if (connection.State == ConnectionState.Open)
                    connection.Close();
                connection.ConnectionString = connectionString;
                SqlCommand sqlCommand = new SqlCommand(commandText, connection);
                sqlCommand.Connection.Open();
                result = Convert.ToInt32(sqlCommand.ExecuteScalar());
                sqlCommand.Connection.Close();
                return result;
            }
            catch (Exception oeException)
            {
                throw new Exception(oeException.Message, oeException);
            }
        }

        /// <summary>
        /// 用数据库管理员的账号检测数据库是否存在
        /// </summary>
        /// <returns></returns>
        protected int CheckDatabaseExistsByDbManager_ajax()
        {
            int result = 0;
            try
            {
                connectionString = string.Format(@"Data Source={0};User ID={1};Password={2};Initial Catalog={3};Pooling=false",
                                          Request.QueryString["sql_ip"], Request.QueryString["sql_manager"], Request.QueryString["sql_managerpassword"], Request.QueryString["sql_name"]);
                commandText = string.Format("SELECT DB_ID('{0}')", Request.QueryString["sql_name"]);
                result = ExcuteReader(commandText, connectionString);
            }
            catch (Exception)
            {
                return result;
            }
            return result;
        }

        /// <summary>
        /// 检查数据库用户是否存在（ajax使用）
        /// </summary>
        /// <returns></returns>
        protected bool CheckDbUserConnection()
        {
            connection.ConnectionString = string.Format(@"Data Source={0};User ID={1};Password={2};Initial Catalog={3};Pooling=false",
                                                 Request.QueryString["sql_ip"], Request.QueryString["sql_username"], Request.QueryString["sql_password"], "master");
            try
            {
                connection.Open();
            }
            catch (Exception)
            {

                return false;
            }
            return true;
        }

        /// <summary>
        /// 选择自动创建数据库时，需要检测的内容
        /// </summary>
        protected void CheckBoxChecked()
        {
            if (Request.QueryString["sql_password"] != Request.QueryString["sql_confirmPassword"])
            {
                Response.Write("{\"Result\":false,\"Message\":\"两次密码输入不一致！请重新填写\"}");
                Response.End();
            }
            else if (Request.QueryString["sql_managerpassword"].IsEmpty())
            {
                Response.Write("{\"Result\":false,\"Message\":\"数据库管理员的密码不能为空！请重新填写\"}");
                Response.End();
            }
            else if (!CheckDbManagerInfo())//指定数据库管理员账号错误（密码错误或者没有建库权限）
            {
                Response.Write("{\"Result\":false,\"Message\":\"数据库管理员密码错误，或者没有建库权限\"}");
                Response.End();
            }
            else if (Request.QueryString["sql_username"] == "sa" && !CheckDbUserConnection())
            {
                Response.Write("{\"Result\":false,\"Message\":\"不能创建数据库用户名，sa为SQL SERVER保留账号；或者是密码填写错误！\"}");
                Response.End();
            }
            else if (CheckDatabaseExistsByDbManager_ajax() != 0) //指定数据库存在
            {
                Response.Write("{\"Result\":false,\"Exists\":true,\"Message\":\"指定数据库已存在，是否继续并覆盖？\"}");
                Response.End();
            }
        }

        /// <summary>
        /// 检测数据库是否存在
        /// </summary>
        /// <returns></returns>
        protected int CheckDatabaseExists()
        {
            int result = 0;
            try
            {
                connectionString = string.Format(@"Data Source={0};User ID={1};Password={2};Initial Catalog={3};Pooling=false",
                                          Request.QueryString["sql_ip"], Request.QueryString["sql_username"], Request.QueryString["sql_password"], Request.QueryString["sql_name"]);
                commandText = string.Format("SELECT DB_ID('{0}')", Request.QueryString["sql_name"]);
                result = ExcuteReader(commandText, connectionString);
                //EditDntConfig(Request["sql_ip"], Request["sql_username"], Request["sql_password"], Request["sql_name"], Request["table_prefix"]);//执行成功后，将数据库连接信息写入DNT.config文件
            }
            catch (Exception)
            {
                Response.Write("{\"Result\":false,\"Message\":\"数据库不存在！请重新填写；或者选择自动创建数据库\"}");
                Response.End();
                return result;
            }
            if (result == 0)
            {
                Response.Write("{\"Result\":false,\"Message\":\"数据库不存在！请重新填写；或者选择自动创建数据库\"}");
                Response.End();
                return result;
            }
            else
            {
                Response.Write("{\"Result\":true,\"Message\":true}");
                Response.End();
                return result;
            }
        }

        #endregion

        /// <summary>
        /// CMS安装文件标题
        /// </summary>
        public static string InstallTiele
        {
            get
            {
                return "YorkCMS安装";
            }
        }
        /// <summary>
        /// 安装向导
        /// </summary>
        /// <param name="intIndex"></param>
        /// <returns></returns>
        public static string InstallLoadInfo(int intIndex)
        {
            StringBuilder oStrBud = new StringBuilder();
            oStrBud.Append(@"
                            <div class='side s_clear'>
                                <div class='side_bar'>
                                    <ul>
                                        <li $1$>欢迎</li>
                                        <li $5$>用户信息</li>
                                        <li $2$>环境检测</li>
                                        <li $3$>CMS设置信息</li>
                                        <li $4$>数据库信息</li>
                                    </ul>
                                    <div class='copy'>河南约克信息技术有限公司</div>
                                </div>
                            </div>
                    ");
            oStrBud.Replace("$" + intIndex.ToString() + "$", "class=\"currentitem\"");
            oStrBud.Replace("$1$", "");
            oStrBud.Replace("$2$", "");
            oStrBud.Replace("$3$", "");
            oStrBud.Replace("$4$", "");
            oStrBud.Replace("$5$", "");
            return oStrBud.ToString();
        }

        #region 环境检验

        /// <summary>
        /// 环境检验
        /// </summary>
        /// <param name="error"></param>
        /// <returns></returns>
        public static string InitialSystemValidCheck(ref bool error)
        {
            error = false;
            StringBuilder sb = new StringBuilder();
            HttpContext context = HttpContext.Current;
            string filename = null;
            if (context != null)
                filename = Common.Util.GetMapPath("/CMSConfig.config");
            else
                filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DNT.config");

            //系统BIN目录检查
            sb.Append(IISSystemBINCheck(ref error));

            //检查系统目录的有效性
            string folderstr = "cms,js,publish,App_Themes,bin,html,resource";
            foreach (string foldler in folderstr.Split(','))
            {
                if (!SystemFolderCheck("/" + foldler))
                {
                    sb.Append("<li><cite><img src=\"images/error.gif\" alt=\"失败\"/></cite><a href=\"#\">对 " + foldler + " 目录没有写入和删除权限!</a></li>");
                    error = true;
                    isError = 1;
                }
                else
                {
                    sb.Append("<li><cite><img src=\"images/ok.gif\" alt=\"成功\"/></cite><a href=\"#\">对 " + foldler + " 目录权限验证通过!</a></li>");
                }
            }
            string filestr = "Advertisement.config,BaseParam.config,CacheSetting.config,ContentEditor.config,ContentPager.config,DB.config,FieldSetting.config,FieldType.config,Plugin.config,PSNType.config,Recomment.config,Syslog.config,sysmenu.config,TemplateVars.config,WordReplaceType.config,Temp.config";
            foreach (string file in filestr.Split(','))
            {
                if (!SystemFileCheck("/cms/config/" + file))
                {
                    sb.Append("<li><cite><img src=\"images/error.gif\" alt=\"失败\"/></cite><a href=\"#\">>对 " + file + " 目录没有写入和删除权限!</a></li>");
                    error = true;
                    isError = 1;
                }
                else
                {
                    sb.Append("<li><cite><img src=\"images/ok.gif\" alt=\"成功\"/></cite><a href=\"#\">对 " + file + " 目录权限验证通过!</a></li>");
                }
            }

            if (!SystemFileCheck("/CMSConfig.config"))
            {
                sb.Append("<li><cite><img src=\"images/error.gif\" alt=\"失败\"/></cite><a href=\"#\">对 CMSConfig.config 文件没有写入的权限!</a></li>");
                error = true;
                isError = 1;
            }

            if (!TempTest())
            {
                sb.Append("<li><cite><img src=\"images/error.gif\" alt=\"失败\"/></cite><a href=\"#\">>您没有对 " + Path.GetTempPath() + " 文件夹访问权限，详情参见安装文档.</a></li>");
                error = true;
                isError = 1;
            }
            return sb.ToString();
        }

        #endregion
    }
}